package com.zn.listener;

import com.alibaba.fastjson.JSONObject;
import com.zn.socket.SocketHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 订阅到redis消息
 */
@Component
public class RedisReceiver {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisReceiver.class);
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Value("${trade.socket.host}")
    private String host;
    @Value("${trade.socket.port}")
    private String port;
    /**
     * 合约code和变更后的chg值
     * @param chgDate
     */
    public void sendUpdateChg(String chgDate){
        JSONObject json = JSONObject.parseObject(chgDate);
        String contractCode=json.get("contractCode").toString();
        String chgValue=json.get("chgValue").toString();
        /**一次只能一台机器处理，分布式锁**/
        boolean lock = redisTemplate.opsForValue().setIfAbsent("SENDUPDATECHG-LOCK-KEY:"+contractCode,"LOCK");
        if(lock){
            redisTemplate.expire("SENDUPDATECHG-LOCK-KEY:"+contractCode, 60, TimeUnit.SECONDS);
            LOGGER.info("接受到来自管理端的数据:" + chgDate);
            try {
                //拼接给C++的字符串 chg|合约|涨跌幅限制
                String dataStr="symbolChg|"+contractCode+"|"+chgValue;
                SocketHandler socketHandler= null;
                socketHandler = SocketHandler.getInstance(host,Integer.valueOf(port));
                /**判断是否断开连接，断开返回true,没有返回false**/
                boolean flag=socketHandler.isServerClose();
                if(flag){
                    throw new Exception("sendUpdateChg socket close.........");
                }
                LOGGER.info("targetProfit dataStr:" + dataStr);
                socketHandler.sendMessage(dataStr);
                //执行完成释放锁
                redisTemplate.delete("SENDUPDATECHG-LOCK-KEY:"+contractCode);
            }catch (Exception e){
                LOGGER.info("sendUpdateChg socket close........." + e);
            }
        }
    }

}